//
//  YLAppUtils.m
//  yuLink
//
//  Created by aiwoba on 2021/3/5.
//

#import "YLAppUtils.h"
#import "SAMKeychain.h"
#import "YYTextLayout.h"

@implementation YLAppUtils

//+ (BOOL)openMessageNotificationService
//{
//    BOOL isOpen = NO;
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
//    UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
//    if (setting.types != UIUserNotificationTypeNone) {
//        isOpen = YES;
//    }
//#else
//    UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
//    if (type != UIRemoteNotificationTypeNone) {
//        isOpen = YES;
//    }
//#endif
//    return isOpen;
//}


// 检查是否有push推送权限
//- (BOOL)checkCurrentNotificationStatus{
//    BOOL isOpen = NO;
//    if (@available(iOS 10 , *)){
//        [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
//            if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined){
//                // 未选择
//            }else if (settings.authorizationStatus == UNAuthorizationStatusDenied){
//                // 没权限
//            }else if (settings.authorizationStatus == UNAuthorizationStatusAuthorized){
//                // 已授权
////                [self requestNotification];
//          
//            }
//        }];
//    }
////    else if (@available(iOS 8 , *))
////    {
////        UIUserNotificationSettings * setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
////        if (setting.types == UIUserNotificationTypeNone) {
////            // 没权限
////        }else{
////            // 已授权
//////            [self requestNotification];
////            isOpen = YES;
////        }
////    }
////    else{
////        UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
////        if (type == UIUserNotificationTypeNone)
////        {
////            // 没权限
////        }
////    }
//    
//    
//    
//}


// 字体
+ (UIFont *)ylFontRegular:(CGFloat)fontSize {
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        return [UIFont fontWithName:@"PingFangSC-Regular" size:fontSize];
    }
    return [UIFont systemFontOfSize:fontSize];
}

+ (UIFont *)ylFontMedium:(CGFloat)fontSize {
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        return [UIFont fontWithName:@"PingFangSC-Medium" size:fontSize];
    }
    
    return [UIFont boldSystemFontOfSize:fontSize];
}

+ (UIFont *)ylFontLight:(CGFloat)fontSize {
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        return [UIFont fontWithName:@"PingFangSC-Light" size:fontSize];
    }
    
    return [UIFont boldSystemFontOfSize:fontSize];
}

+ (UIFont *)ylFontSemibold:(CGFloat)fontSize {
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        return [UIFont fontWithName:@"PingFangSC-Semibold" size:fontSize];
    }
    
    return [UIFont boldSystemFontOfSize:fontSize];
}

+ (UIFont *)ylFontNumberBold:(CGFloat)fontSize {
    return [UIFont fontWithName:@"DIN-Bold" size:fontSize];
}

+ (UIFont *)ylFontNumberRegular:(CGFloat)fontSize {
    return [UIFont fontWithName:@"DIN-Regular" size:fontSize];
}
// 判断是否为空
+ (BOOL)judgeStrIsEmpty:(NSString *)str {
    if (str == nil) {
        return YES;
    }
    if (str == NULL) {
        return YES;
    }
    if ([str isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if (![str isKindOfClass:[NSString class]]) {
        str = [NSString stringWithFormat:@"%@", str];
    }
    if ([[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
        return YES;
    }
    
    return NO;
}

+ (BOOL)isIphonex {
    if (@available(iOS 11.0, *)) {
        UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
        // 获取底部安全区域高度，iPhone X 竖屏下为 34.0，横屏下为 21.0，其他类型设备都为 0
        CGFloat bottomSafeInset = keyWindow.safeAreaInsets.bottom;
        if (bottomSafeInset > 0) {
            return YES;
        }
    }
    return NO;
}
// 过滤null和nil
+ (NSString *)filterNull:(NSString *)str{
    if (![str isKindOfClass:[NSString class]]) {
        str = [NSString stringWithFormat:@"%@", str];
    }
    
    if (str == nil || [str isEqual:[NSNull null]] || [str isEqualToString:@"(null)"]||[str isEqualToString:@"<null>"]||str.length==0) {
        return @"";
    }
    
    return str;
}



+ (BOOL)judgeInfoIsEmpty:(id )info
{
    if (info == nil) {
        return YES;
    }
    
    if (info == NULL) {
        return YES;
    }
    
    if ([info isKindOfClass:[NSNull class]]) {
        return YES;
    }
    return NO;
    
}


#pragma mark -字典转换成json串
+(NSString *)dictionaryToJsonString:(NSDictionary *)dict{
    
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
#pragma mark -数组转换成json串
+(NSString *)arrayToJsonString:(NSArray *)array{
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];;
}

///颜色转image
+(UIImage*)ylCreateImageWithColor:(UIColor*)color{
    CGRect rect=CGRectMake(0.0f,0.0f,1.0f,1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;

}
 
//数组转为json字符串
+(NSString *)arrayToJSONString:(NSArray *)array {
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *jsonTemp = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    //    NSString *jsonResult = [jsonTemp stringByReplacingOccurrencesOfString:@" " withString:@""];
    return jsonTemp;
}

+ (CGFloat)textWidthWithAttString:(NSAttributedString *)attString height:(CGFloat)height {
    YYTextLayout *textLayout = [YYTextLayout layoutWithContainerSize:CGSizeMake(MAXFLOAT, height) text:attString];
    return textLayout.textBoundingSize.width;
}

+ (CGFloat)textWidthWithAttString:(NSAttributedString *)attString height:(CGFloat)height maximumLineNum:(NSUInteger)lineNum {
    YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(MAXFLOAT, height)];
//    container.maximumNumberOfRows = lineNum;
    YYTextLayout *textLayout = [YYTextLayout layoutWithContainer:container text:attString];
    return textLayout.textBoundingSize.width;
}

+ (CGFloat)textHeightWithAttString:(NSAttributedString *)attString width:(CGFloat)width maximumLineNum:(NSUInteger)lineNum {
    YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(width, MAXFLOAT)];
    container.maximumNumberOfRows = lineNum;
    YYTextLayout *textLayout = [YYTextLayout layoutWithContainer:container text:attString];
    return textLayout.textBoundingSize.height;
}
+ (CGSize)textSizeWithAttString:(NSAttributedString *)attString width:(CGFloat)width maximumLineNum:(NSUInteger)lineNum {
    YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(width, MAXFLOAT)];
    container.maximumNumberOfRows = lineNum;
    YYTextLayout *textLayout = [YYTextLayout layoutWithContainer:container text:attString];
    return textLayout.textBoundingSize;
}

+ (CGSize)labelTextSize:(UILabel *)label {
    if (!label) {
        return CGSizeMake(0, 0);
    }
    
    UILabel *templabel = [[UILabel alloc] initWithFrame:label.frame];
    templabel.textAlignment = label.textAlignment;
    templabel.font = label.font;
    templabel.numberOfLines = label.numberOfLines;
    templabel.lineBreakMode = label.lineBreakMode;
    if (![YLAppUtils judgeStrIsEmpty:label.text]) {
        templabel.text = label.text;
    }
    
    if (![YLAppUtils judgeStrIsEmpty:label.attributedText.string]) {
        templabel.attributedText = label.attributedText;
    }
    
    [templabel sizeToFit];
    
    return templabel.frame.size;
}
+ (BOOL)isIpad {
    NSString *deviceType = [UIDevice currentDevice].model;
    if([deviceType isEqualToString:@"iPad"]) {
        return YES;
    }
    return NO;
}

+ (NSString *)URLDecode:(NSString *)undecodedURL {
    NSString* result = [undecodedURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSParameterAssert(result);
    return result;
}
//获取客户端APP版本号
+ (NSString *)getAppVersion {
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *appVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
    return appVersion;
}
//获取客户端设备唯一标识
+ (NSString *)getUUID {
    NSString * currentDeviceUUIDStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"];
    if ([YLAppUtils judgeStrIsEmpty:currentDeviceUUIDStr]) {
         NSString * currentDeviceUUIDStrKey = [SAMKeychain passwordForService:@"com.re.reelep" account:@"uuid"];
        if ([YLAppUtils judgeStrIsEmpty:currentDeviceUUIDStrKey]) {
            NSUUID * currentDeviceUUID  = [UIDevice currentDevice].identifierForVendor;
            currentDeviceUUIDStr = currentDeviceUUID.UUIDString;
            currentDeviceUUIDStr = [currentDeviceUUIDStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
            currentDeviceUUIDStr = [currentDeviceUUIDStr lowercaseString];
            currentDeviceUUIDStr = [NSString stringWithFormat:@"%@%@",currentDeviceUUIDStr,[self getCurrentTimes]];
            [SAMKeychain setPassword: currentDeviceUUIDStr forService:@"com.re.reelep" account:@"uuid"];
            [[NSUserDefaults standardUserDefaults] setObject:currentDeviceUUIDStr forKey:@"uuid"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        } else {
            currentDeviceUUIDStr = currentDeviceUUIDStrKey;
        }
        
    }
    return currentDeviceUUIDStr;
}



+(NSString*)getCurrentTimes{
    
    int n = (arc4random() % 10000);
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    NSString *timeStamp = [NSString stringWithFormat:@"%.f",time];
    
    NSString *currentTimeString = [NSString stringWithFormat:@"%@%d",timeStamp,n];
    return currentTimeString;
    
}

//获取客户端操作系统的版本号
+ (NSString *)getIOSVersion {
     return [[UIDevice currentDevice] systemVersion];
}

//获取当前屏幕显示的viewcontroller
+ (UIViewController *)getCurrentVC {
    UIViewController *rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
    
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    
    return currentVC;
}

+ (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC {
    UIViewController *currentVC;
    
    if ([rootVC presentedViewController]) {
        // 视图是被presented出来的
        
        rootVC = [rootVC presentedViewController];
    }
    
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
        
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
        
    } else {
        // 根视图为非导航类
        
        currentVC = rootVC;
    }
    
    return currentVC;
}

+ (void)pasteboardURLString:(NSString *)pageUrl {
    UIPasteboard *copyBoard = [UIPasteboard generalPasteboard];
    copyBoard.string = pageUrl;
    [BaseToastView showToastWithText:@"复制成功" Type:YLToastTypeShort ToView:nil];
}

+(NSString *)subStringWith:(NSString *)string ToIndex:(NSInteger)index{

    NSString *result = string;
    if (result.length > index) {
        NSRange rangeIndex = [result rangeOfComposedCharacterSequenceAtIndex:index];
        result = [result substringToIndex:(rangeIndex.location)];
    }

    return result;
}
 
#pragma mark - 权限检查
+(void)checkAudioAuthorization {
     AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (statusAudio == AVAuthorizationStatusDenied) {
         [BaseToastView showToastWithText:@"获取麦克风权限失败，请前往隐私-麦克风设置里面打开应用权限" Type:YLToastTypeShort ToView:nil];
    }else if(statusAudio == AVAuthorizationStatusNotDetermined){
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
         }];
    }
}

+ (void)checkVideoAuthorization {
     //是否有摄像头权限
    AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (statusVideo == AVAuthorizationStatusDenied) {
        [BaseToastView showToastWithText:@"获取摄像头权限失败，请前往隐私-相机设置里面打开应用权限" Type:YLToastTypeShort ToView:nil  ];
    }else if(statusVideo == AVAuthorizationStatusNotDetermined){
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
         }];
    }
}

//+(void)toVideoVC:(REDramaModel *)model{
//    
//    VEShortVideoViewController *shortVideoViewController = [VEShortVideoViewController new];
//    shortVideoViewController.dramaModel = model;
//    PUSHCONTROLLER(shortVideoViewController);
//}
 
 
@end
